package com.mulanweb.api.module.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.controller.Support2Controller;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.utils.NumberFormatterUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * Created by Administrator on 2016/8/19.
 */
@ValidateFile
public class TicketController extends BaseController {

    public void searchKeyWord() {
        /**
         * 搜索关键字
         */
        String searchContent = getPara("searchKeyWord");
        Long typeId = getParaToLong("typeId");

        String searchTag = null;
        if(StringUtils.isNotBlank(searchContent)){
            searchTag="%" + searchContent + "%";
        }

        List<Long> cityIds = new ArrayList<>();
        List<Long> scopIds = new ArrayList<>();
        List<Long> sellerIds = new ArrayList<>();
        List<City> cityList = City.dao.find("SELECT * FROM city WHERE name_cn LIKE ? AND delete_time IS NULL ", searchTag);
        for (City city : cityList) {
            cityIds.add(city.getId());
        }

        List<ScenicSpot> scenicSpotList = ScenicSpot.dao.find("SELECT * FROM scenic_spot WHERE scenic_name LIKE ? ", searchTag);
        for (ScenicSpot scenicSpot : scenicSpotList) {
            scopIds.add(scenicSpot.getId());
        }

        List<Seller> sellerList = Seller.dao.find("SELECT * FROM seller WHERE seller_name like ? AND delete_time IS NULL", searchTag);
        for (Seller seller : sellerList) {
            sellerIds.add(seller.getId());
        }

        Support2Controller helper2 = new Support2Controller("ticket","create_time desc");

        helper2 = new Support2Controller("ticket", "price");
        helper2.addIsNullCondition("delete_time");

        helper2.addOrLikeCondition("title",searchContent);
        helper2.addOrLikeCondition("title_en",searchContent);

        helper2.addOrLikeCondition("cp_td",searchContent);
        helper2.addOrLikeCondition("xc_ap",searchContent);
        helper2.addOrLikeCondition("fy_sm",searchContent);
        helper2.addOrLikeCondition("yd_xz",searchContent);
        helper2.addOrLikeCondition("tg_gz",searchContent);
        helper2.addOrLikeCondition("zy_sx",searchContent);

        /*helper2.addOrCondition("city_id","$in","");
        helper2.addOrInConditionToLong("scenic_spot_id",scopIds);
        helper2.addOrInConditionToLong("seller_id",sellerIds);*/

        helper2.addCondition("surplus_total",">",0);
        helper2.addEqualsCondition("basic_commodity",1);
        helper2.addEqualsCondition("type_id",typeId);

        Page<Ticket> page = Ticket.dao.paginate(getPageNumber(), getPageSize(), helper2.getSqlSelect(), helper2.getSqlExceptSelect2(), helper2.getQueryParas());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ReturnCode", 1);
        //map.put("TotalPage", Math.ceil((double) listTotal.size() / (double) getPageSize()));
        map.put("TotalPage", page.getTotalPage());
        map.put("TotalRow", page.getTotalRow());
        map.put("PageNumber", getPageNumber());
        map.put("PageSize", getPageSize());
        map.put("DataList", page.getList());

        SearchHistory searchHistory = SearchHistory.dao.findFirst("SELECT * FROM search_history WHERE content = ?",searchContent);
        String openId = super.getSessionAttr("openId");
        User user = User.dao.findFirst("SELECT * FROM user where open_id = ?", openId);
        if(searchHistory == null && UserHandler.userNotNull(openId)){
            searchHistory = new SearchHistory();
            searchHistory.setContent(searchContent);
            searchHistory.setUserId(user.getId());
            searchHistory.setCreateTime(new Date());
            searchHistory.save();
        }
        renderJson(map);
    }
    @ValidateForm
    public void search(){
        SQLGenerateHelper helper = null;
        int orderBy = getParaToInt("orderBy") != null ? getParaToInt("orderBy") : 1;
        if (orderBy == 1) {
            //orderBy = 1  按价格升序
            helper = new SQLGenerateHelper("ticket", "price");
            helper.addIsNullCondition("delete_time");
        } else if (orderBy == 2) {
            //orderBy = 2  按人气降序序
            helper = new SQLGenerateHelper("ticket t", "(SELECT COUNT(*) FROM collection c WHERE t.id = c.target_id AND c.type_id=23)  DESC");
            helper.addLikeCondition("title", getPara("ticketTitle"));
            helper.addEqualsCondition("type_id", getParaToLong("typeId"));
            helper.addCondition("surplus_total", ">", 0);
            helper.addIsNullCondition("delete_time");
            helper.addEqualsCondition("city_id", getPara("cityId"));
            helper.addEqualsCondition("basic_commodity", 1);
            /*helper.addCondition("start_time","<=",new Date());*/
            //helper.addCondition("end_time",">=",new Date());
            List<Object> para = new ArrayList<>();
            if (StrKit.notNull(helper.getQueryParas()) && helper.getQueryParas().length > 0) {
                for (Object tt : helper.getQueryParas()) {
                    para.add(tt);
                }
            }
            para.add(getPageNumber() * getPageSize() - getPageSize());
            para.add(getPageSize());
            List<Ticket> list = Ticket.dao.find(helper.getSqlSelect() + helper.getSqlExceptSelect() + " LIMIT ?,?", para.toArray());
            List<Ticket> listTotal = Ticket.dao.find(helper.getSqlSelect() + helper.getSqlExceptSelect(), helper.getQueryParas());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ReturnCode", 1);
            map.put("TotalPage", Math.ceil((double) listTotal.size() / (double) getPageSize()));
            map.put("TotalRow", listTotal.size());
            map.put("PageNumber", getPageNumber());
            map.put("PageSize", getPageSize());
            map.put("DataList", list);
            renderJson(map);
            return;
        } else if (orderBy == 3) {
            //orderBy = 3  按好评降序序
            helper = new SQLGenerateHelper("ticket t", "(SELECT SUM(e.score) FROM content_evaluate e WHERE t.id = e.target_id AND e.type_id=23)  DESC");
            helper.addLikeCondition("title", getPara("ticketTitle"));
            helper.addEqualsCondition("type_id", getParaToLong("typeId"));
            helper.addEqualsCondition("city_id", getPara("cityId"));
            helper.addCondition("surplus_total", ">", 0);
            helper.addIsNullCondition("delete_time");
            helper.addEqualsCondition("basic_commodity", 1);
            /*helper.addCondition("start_time","<=",new Date());*/
            //helper.addCondition("end_time",">=",new Date());
            List<Object> para = new ArrayList<>();
            if (StrKit.notNull(helper.getQueryParas()) && helper.getQueryParas().length > 0) {
                for (Object tt : helper.getQueryParas()) {
                    para.add(tt);
                }
            }
            para.add(getPageNumber() * getPageSize() - getPageSize());
            para.add(getPageSize());
            List<Ticket> list = Ticket.dao.find(helper.getSqlSelect() + helper.getSqlExceptSelect() + " LIMIT ?,?", para.toArray());
            List<Ticket> listTotal = Ticket.dao.find(helper.getSqlSelect() + helper.getSqlExceptSelect(), helper.getQueryParas());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ReturnCode", 1);
            map.put("TotalPage", Math.ceil((double) listTotal.size() / (double) getPageSize()));
            map.put("TotalRow", listTotal.size());
            map.put("PageNumber", getPageNumber());
            map.put("PageSize", getPageSize());
            map.put("DataList", list);
            renderJson(map);
            return;
        } else if (orderBy == 4) {
            //orderBy = 4  按创建时间升序
            String longitude1 = getPara("longitude");
            String latitude1 = getPara("latitude");
            Double longitude = Double.parseDouble(longitude1);
            Double latitude = Double.parseDouble(latitude1);

            helper = new SQLGenerateHelper("ticket tt");
            helper.addLikeCondition("title", getPara("ticketTitle"));
            helper.addEqualsCondition("type_id", getParaToLong("typeId"));
            helper.addEqualsCondition("city_id", getPara("cityId"));
            helper.addCondition("surplus_total", ">", 0);
            helper.addIsNullCondition("delete_time");
            helper.addEqualsCondition("basic_commodity", 1);
            /*helper.addCondition("start_time","<=",new Date());*/
            //helper.addCondition("end_time",">=",new Date());
            List<Object> para = new ArrayList<>();
            para.add(longitude);
            para.add(longitude);
            para.add(latitude);
            if (StrKit.notNull(helper.getQueryParas()) && helper.getQueryParas().length > 0) {
                for (Object tt : helper.getQueryParas()) {
                    para.add(tt);
                }
            }
            para.add(getPageNumber() * getPageSize() - getPageSize());
            para.add(getPageSize());
            List<Ticket> list = Ticket.dao.find("SELECT *,(SELECT ((6378.138*2*ASIN(SQRT(POW(SIN((?*PI()/180-latitude*PI()/180)/2),2)+COS(?*PI()/180)*COS(latitude*PI()/180)*POW(SIN((?*PI()/180-longitude*PI()/180)/2),2)))*1000)) FROM scenic_spot WHERE id = tt.scenic_spot_id) juli" + helper.getSqlExceptSelect() + "ORDER BY juli LIMIT ?,?", para.toArray());
            List<Ticket> listTotal = Ticket.dao.find(helper.getSqlSelect() + helper.getSqlExceptSelect(), helper.getQueryParas());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ReturnCode", 1);
            map.put("TotalPage", Math.ceil((double) listTotal.size() / (double) getPageSize()));
            map.put("TotalRow", listTotal.size());
            map.put("PageNumber", getPageNumber());
            map.put("PageSize", getPageSize());
            map.put("DataList", list);
            renderJson(map);
            return;


            /*List<ScenicSpot> scenicSpots = ScenicSpot.dao.find("SELECT * FROM scenic_spot ORDER BY ((6378.138*2*ASIN(SQRT(POW(SIN((?*PI()/180-latitude*PI()/180)/2),2)+COS(?*PI()/180)*COS(latitude*PI()/180)*POW(SIN((?*PI()/180-longitude*PI()/180)/2),2)))*1000))",longitude,longitude,latitude);
            for(ScenicSpot scenicSpot : scenicSpots){
                List<Ticket> tickets = Ticket.dao.find("SELECT * FROM ticket WHERE city_id = ?",scenicSpot.getCityId());
            }*/
            //helper = new SQLGenerateHelper("ticket", "create_time desc");
        }
        //helper = new SQLGenerateHelper("ticket", "create_time desc");
        helper.addEqualsCondition("city_id", getPara("cityId"));
        helper.addLikeCondition("title", getPara("ticketTitle"));
        helper.addEqualsCondition("type_id", getParaToLong("typeId"));
        helper.addCondition("surplus_total", ">", 0);
        helper.addIsNullCondition("delete_time");
        helper.addEqualsCondition("basic_commodity", 1);
        /*helper.addCondition("start_time","<=",new Date());*/
        //helper.addCondition("end_time",">=",new Date());
        Page<Ticket> page = Ticket.dao.paginate(getPageNumber(), getPageSize(), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ReturnCode", 1);
        map.put("TotalPage", page.getTotalPage());
        map.put("TotalRow", page.getTotalRow());
        map.put("PageNumber", page.getPageNumber());
        map.put("PageSize", page.getPageSize());
        map.put("DataList", page.getList());
        renderJson(map);
    }

    public void searchUserHistory(){
        String openId = super.getSessionAttr("openId");
        User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ?",openId);
        if(UserHandler.userNotNull(openId)){
            SQLGenerateHelper helper = new SQLGenerateHelper("search_history","create_time desc");
            helper.addEqualsCondition("user_id",user.getId());
            Page<SearchHistory> page = SearchHistory.dao.paginate(1,10,helper.getSqlSelect(),helper.getSqlExceptSelect(),helper.getQueryParas());
            returnPageModelJson(page);
        }else{
            returnFailureJson();
        }
    }

    public void cleanSearchHistory(){
        String openId = super.getSessionAttr("openId");
        User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ?",openId);
        if(UserHandler.userNotNull(openId)){
            List<SearchHistory> list = SearchHistory.dao.find("SELECT * FROM search_history WHERE user_id = ?",user.getId());
            for(SearchHistory s : list){
                s.delete();
            }
            returnSuccessJson();
        }else{
            returnFailureJson();
        }
    }

    /**
     * 返回ticket详细信息以及他的好评平均分
     */
    public void getDetail() {
        Long targetId = getParaToLong("targetId");//被评论者的id
        Ticket ticket = Ticket.dao.findById(targetId);
        List<ContentEvaluate> evaluates = ContentEvaluate.dao.find("select * from content_evaluate where type_id = 23 and target_id = ?", targetId);
        float score = 0F;
        int i = 0;
        for (ContentEvaluate tt : evaluates) {
            score = tt.getScore() + score;
            i++;
        }
        score = NumberFormatterUtil.floatLengthController(score > 0 ? score / i : 0, 1);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("score", score);
        map.put("target", ticket);
        map.put("position", ScenicSpot.dao.findById(ticket.getScenicSpotId()).getPosition());
        String openId = super.getSessionAttr("openId"); //"oULNBwOvt_D2A_8se1bQOQ06ky0w";//
        if (openId != null) {
            User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ? ", openId);
            if (user.getLongitude() != null) {
                Double tt = (ScenicSpot.dao.find("SELECT ROUND((6378.138*2*ASIN(SQRT(POW(SIN((121.436893*PI()/180-latitude*PI()/180)/2),2)+COS(121.436893*PI()/180)*COS(latitude*PI()/180)*POW(SIN((31.207601*PI()/180-longitude*PI()/180)/2),2)))*1000)) juli " +
                        " FROM scenic_spot WHERE id = ?", ticket.getScenicSpotId()).get(0).get("juli"));
                map.put("distance", "(" + (tt / 1000) + "km)");
            }
        }
        returnSuccessJson(map);
    }
}
